import nme.Assets;
import nme.display.Sprite;
import nme.display.Graphics;
import nme.display.Bitmap;
import nme.display.BitmapData;
import nme.display.BlendMode;

import nme.geom.ColorTransform;
import nme.geom.Transform;
import nme.geom.Rectangle;
import nme.geom.Matrix;
import nme.geom.Point;

import nme.display.Tilesheet;

class FrameData
{
	public var _id:String;
	public var _name:String;
	public var _sprite:SpriteData;
	public var _modules_id:Array <String>;
	public var _modules_matrix (default, null):Array <Matrix>;
	public var _modules_colortransform:Array <ColorTransform>;
	public var _bound:Rectangle;
	public var _bitmapdata:BitmapData;
	
	private function new (id:String, name:String, spr:SpriteData)
	{
		_id = id;
		_name = name;
		_sprite = spr;
		_modules_id = new Array<String> ();
		_modules_matrix = new Array <Matrix> ();
		_bound = new Rectangle (0, 0, 0, 0);
	}
	
	private function readModuleData (moduleXml:Xml):Void
	{
		_modules_id.push (moduleXml.get("id"));
		_modules_matrix.push (
			new Matrix (
				Std.parseFloat (moduleXml.get("a")),
				Std.parseFloat (moduleXml.get("b")),
				Std.parseFloat (moduleXml.get("c")),
				Std.parseFloat (moduleXml.get("d")),
				Std.parseFloat (moduleXml.get("tx")),
				Std.parseFloat (moduleXml.get("ty"))
			)
		);
	}
	
	public static function create (frameXml:Xml, spr:SpriteData):FrameData
	{
		var frame:FrameData = new FrameData (frameXml.get("id"), frameXml.get("name"), spr);
		
		var modules:Iterator<Xml> = frameXml.elementsNamed("module");		
		for (m in modules) frame.readModuleData (m);
		
		return frame;
	}
	
	public function toGraphics (graphics:Graphics, ?transform:Transform):Void
	{
		// graphics.lineStyle (1, 0xFF0000, 0.5);
		graphics.beginBitmapFill (_sprite._src, null, false, true);
		for (mid in 0 ... _modules_id.length)
		{
			var md:ModuleData = _sprite._modules.get (_modules_id [mid]);
			var m:Matrix = _modules_matrix [mid];
			graphics.drawTriangles (md.vertices (m), [0, 1, 2, 0, 2, 3], md.uvtData);
		}
		graphics.endFill();
	}
	
	public function getTileData ():Array <Float>
	{
		// var _flag:Int = Tilesheet.TILE_TRANS_2x2;// | Tilesheet.TILE_ALPHA | Tilesheet.TILE_RGB | Tilesheet.TILE_BLEND_ADD;
		// var _tiles:Array<Rectangle> = [];
		var _tileData:Array<Float> = [];
		
		for (mid in 0 ... _modules_id.length)
		{
			var md:ModuleData = _sprite._modules.get (_modules_id [mid]);
			var m:Matrix = _modules_matrix [mid];
			
			// _tiles.push (md.bound.clone());
			_tileData.push (m.tx);
			_tileData.push (m.ty);
			_tileData.push (md.index);
			_tileData.push (m.a);
			_tileData.push (m.b);
			_tileData.push (m.c);
			_tileData.push (m.d);
		}
		
		return _tileData;
	}
	
	public function toBitmapData (bitmap:BitmapData):Void
	{
		
	}
}